import ObjectPool from "./ObjectPool.js";

export default class {
    constructor({ creater, editer, remover, matcher = () => true }) {
        this.list = [];
        this._objectPool = new ObjectPool();
        this._creater = creater;
        this._editer = editer;
        this._remover = remover;
        this._matcher = matcher;
    }
    update(data) {
        /**
         * 回收所有对象
         */
        this._objectPool.recovery(...this.list);
        this.list = data.map((item) => {
            const obj = this._objectPool.create({
                creater: () => this._creater(item),
                matcher: (obj) => this._matcher(obj, item),
            });
            this._editer(obj, item);
            return obj;
        });
        /**
         * 释放剩下的对象
         */
        this._objectPool.clear(this._remover);
    }
    destroy() {
        this.list.forEach(this._remover);
        this.list = [];
    }
    find(item) {
        return this.list.find((obj) => () => this._matcher(obj, item));
    }
}
